package com.cherry.example.network.tcp;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;

/*
传输图片的服务端
*/
public class ImageServer extends Thread {
	
	Socket socket;
	
	
	//用于存储ip地址的。
	static HashSet<String> ips = new HashSet<String>();
	
	public ImageServer(Socket socket){
		this.socket = socket;
	}

	@Override
	public void run() {
		try {
			//获取socket的输出流
			OutputStream socketOut = socket.getOutputStream();
			//获取文件的输入流。
			FileInputStream fileInputStream = new FileInputStream("D:\\张慧雯.jpg");
			byte[] buf = new byte[1024];
			int length = 0;
			
			while((length = fileInputStream.read(buf))!=-1){
				socketOut.write(buf,0,length);
			}
			
			String ip = socket.getInetAddress().getHostAddress();//获取客户端的ip地址。
			if(ips.add(ip)){
				//该ip是不存在的。
				System.out.println("恭喜"+ip+"成功获取到美女！");
				System.out.println("当前获取到图片的人数是："+ ips.size());
			}
			
			
			
		
			//关闭资源
			socket.close();
		
		} catch (IOException e) {
			
		}	
	}
	
	
	public static void main(String[] args) throws IOException {
		//建立服务端
		ServerSocket serverSocket = new ServerSocket(9090);
		while(true){
			//不断的接收客户端的连接
			Socket socket = serverSocket.accept();
			//创建一个线程
			new ImageServer(socket).start();
			
		}
		
	}
	
}
